import json
import requests

from config.config import settings
from src.auth.auth_manager import auth_manager

class APIManager:
    def __init__(self, client_id, client_secret):
        self.MAX_RETRIES = settings.MAX_RETRY_COUNT
        self.client_id = client_id
        self.client_secret = client_secret

    def _make_request(self, method, url, headers, json_data=None):
        for attempt in range(self.MAX_RETRIES):
            try:
                if method == "post":
                    response = requests.post(url, headers=headers, json=json_data)
                elif method == "patch":
                    response = requests.patch(url, headers=headers, json=json_data)
                elif method == "delete":
                    response = requests.delete(url, headers=headers)
                response.raise_for_status()
                return response.json()
            except requests.RequestException as e:
                if attempt < self.MAX_RETRIES - 1:
                    print(f"请求失败，第 {attempt + 1} 次重试: {e}")
                else:
                    print(f"请求失败，已达到最大重试次数: {e}")
        return None

    def create_record(self, object_id, record_data):
        """
        创建记录

        Args:
            object_id (str): 对象ID
            record_data (dict or str): 记录数据，可以是字典或JSON字符串

        Returns:
            dict: 创建的记录数据或None
        """
        token = auth_manager.get_token()
        url = f"{settings.CURD_BASE_URL}/{object_id}/records"
        headers = {"Authorization": token, "Content-Type": "application/json"}
        if not isinstance(record_data, dict):
            record_data = json.loads(record_data)
        data = {"record": record_data}

        return self._make_request("post", url, headers, data)

    def update_record(self, object_id, record_id, record_data):
        """
        更新记录
        
        Args:
            object_id (str): 对象ID
            record_id (str): 记录ID
            record_data (dict or str): 更新的记录数据，可以是字典或JSON字符串
        Returns:
            dict: 更新后的记录数据或None
        """
        token = auth_manager.get_token()
        url = f"{settings.CURD_BASE_URL}/{object_id}/records/{record_id}"
        headers = {"Authorization": token, "Content-Type": "application/json"}
        if not isinstance(record_data, dict):
            record_data = json.loads(record_data)
        data = {"record": record_data}

        return self._make_request("patch", url, headers, data)

    def delete_record(self, object_id, record_id):
        """
        删除记录

        Args:
            object_id (str): 对象ID
            record_id (str): 记录ID
        Returns:
            dict: 删除结果或None
        """
        token = auth_manager.get_token()
        url = f"{settings.CURD_BASE_URL}/{object_id}/records/{record_id}"
        headers = {"Authorization": token}

        return self._make_request("delete", url, headers)

    def query_records(self, object_id, query_keys=["_id"]):
        """
        查询记录

        Args:
            object_id (str): 对象ID
            query_keys (list): 查询的字段列表，默认为["_id"]

        Returns:
            dict: 查询结果或None
        """
        token = auth_manager.get_token()
        if not token:
            return None

        url = f"{settings.CURD_BASE_URL}/{object_id}/records_query"
        headers = {"Authorization": token, "Content-Type": "application/json"}

        # 设置默认查询参数
        query_params = {
            "use_page_token": False,
            "offset": 0,
            "need_total_count": False,
            "filter": {},
            "page_token": "",
            "page_size": 500,
            "query_deleted_record": False,
            "select": query_keys,
        }

        return self._make_request("post", url, headers, query_params)

    def select_by_id(self, object_id : str, record_id : str, query_keys : list=["_id"]):
        """
        查询记录

        Args:
            object_id (str): 对象ID
            record_id (str): 记录ID
            query_keys (list): 查询的字段列表，默认为["_id"]

        Returns:
            dict: 查询结果或None
        """
        token = auth_manager.get_token()
        if not token:
            return None

        url = f"{settings.CURD_BASE_URL}/{object_id}/records_query"
        headers = {"Authorization": token, "Content-Type": "application/json"}

        left_settings = json.dumps(dict({
                            "fieldPath":[{"fieldApiName":"_id" , "objectApiName" : object_id}],
                            "variableApiName":"current_object"
                        }))

        right_settings = json.dumps(dict({
                    "data" : record_id
                }))

        id_equal_condition = {
            "left": {
                "settings": left_settings,
                "type": "metadataVariable"
            },
            "operator": "equals",
            "right": {
                "type": "constant",
                "settings": right_settings
            }
        }

        # print(json.dumps(id_equal_condition))
        conditions = [(id_equal_condition)]

        # print(f"查询条件: {conditions}")

        # 设置默认查询参数
        query_params = {
            "use_page_token": False,
            "offset": 0,
            "need_total_count": False,
            "filter": {
                "conditions": conditions
            },
            "page_token": "",
            "page_size": 200,
            "query_deleted_record": False,
            "select": query_keys,
        }

        return self._make_request("post", url, headers, query_params)
